<?php

namespace app\common\library\wechat;

/**
 * 微信模板消息-公众号
 * Class WxTplMsg
 * @package app\common\library\wechat
 */
class WxTplMsg extends WxBase {
	/**
	 * 发送模板消息
	 * @param array $param
	 * @return bool
	 * @throws \app\common\exception\BaseException
	 */
	public function sendTemplateMessage($params) {


		// 微信接口url
		$accessToken = $this->getAccessTokenWechat();
	


		 //$url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$accessToken}";
		//$url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$accessToken}";
		//$url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token={$accessToken}";
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}"; //公众号模板消息

		//$user_url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$accessToken}";

		//$users_json = $this->post($user_url);
		//$users_array = $this->jsonDecode($users_json);
		//$users = $users_array['data']['openid'];
		//$users=['o8HTX5uyVkndgON-Nm2fdmXN-lKI','o8HTX5s-YfHhgLbSldPvtG21VDCU'];

		$data = $this->createData($params['data']);
		// 构建请求

		$params['data'] = $data;

		$result = $this->post($url, $this->jsonEncode($params));

		// $template = Db::name('template')->where('template_id', $param['template_id'])->value('name');
		// $log = [];
		// $log = $param['data'];
		// $log['template'] = $template;
		// $log['num'] = count($users);
		// $log['create_time'] = time();
		// Db::name('user_push_log')->insert($log);

		// 记录日志
		///$this->doLogs(['describe' => '发送模板消息', 'url' => $url, 'params' => $params, 'result' => $result]);

		  // 记录日志
        log_record(['name' => '发送模板消息', 'url' => $url, 'params' => $params, 'result' => $result]);
		// 返回结果
		$response = $this->jsonDecode($result);

		//print_r($response);exit;
		if (!isset($response['errcode'])) {
			$this->error = 'not found errcode';
			return false;
		}
		if ($response['errcode'] != 0) {
			$this->error = $response['errmsg'];
			return false;
		}
		return true;
	}

	/**
	 * 生成关键字数据
	 * @param $data
	 * @return array
	 */
	private function createData($data) {
		$params = [];
		foreach ($data as $key => $value) {
			$color = '#333333';
			if ($key == 'remark') {
				$color = '#dd514c';
			} elseif ($key == 'keyword1') {
				$color = '#dd514c';
			}
			$params[$key] = [
				'value' => $value,
				'color' => $color,
			];
		}
		// $params['thing1']['value']='XX课程';
		// $params['name2']['value']='刘德华';
		// $params['date3']['value']='2022-11-25 20:00';
		// $params['thing4']['value']='记得准时参加';
		return $params;
	}

}